/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.tracer.core.samplers;

import com.lvyh.lightframe.tracer.core.enums.SamplerType;

import java.util.BitSet;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

public class PercentageBasedSampler implements Sampler {

    public static final String TYPE = SamplerType.PERCENTAGE_BASED.getKey();

    private final AtomicLong counter = new AtomicLong(0);
    private final BitSet sampleDecisions;
    private final Integer percentage;

    public PercentageBasedSampler(Integer percentage) {
        this.percentage = percentage;
        this.sampleDecisions = randomBitSet(100, percentage, new Random());
    }

    @Override
    public TraceSamplerConfig getSampleConfig(String operationName) {
        TraceSamplerConfig traceSamplerConfig = new TraceSamplerConfig();
        traceSamplerConfig.setSamplerType(TYPE);
        traceSamplerConfig.setPercentage(percentage);

        if (this.percentage == 0) {
            traceSamplerConfig.setSampled(false);
            return traceSamplerConfig;
        } else if (this.percentage == 100) {
            traceSamplerConfig.setSampled(true);
            return traceSamplerConfig;
        }

        boolean result = this.sampleDecisions.get((int) (this.counter.getAndIncrement() % 100));
        traceSamplerConfig.setSampled(result);
        return traceSamplerConfig;
    }

    @Override
    public void release() {
    }

    public static BitSet randomBitSet(int size, int cardinality, Random rnd) {
        BitSet result = new BitSet(size);
        int[] chosen = new int[cardinality];
        int i;
        for (i = 0; i < cardinality; ++i) {
            chosen[i] = i;
            result.set(i);
        }
        for (; i < size; ++i) {
            int j = rnd.nextInt(i + 1);
            if (j < cardinality) {
                result.clear(chosen[j]);
                result.set(i);
                chosen[j] = i;
            }
        }
        return result;
    }
}
